import axios from 'axios';
import base from './base';
import router from '../router';

let refresh = false;
let requests = [];
const request = axios.create({
  baseURL: base.API_PREFIX,
  timeout: 5000,
});
// token刷新  https://zhuanlan.zhihu.com/p/91569497
request.interceptors.request.use((config) => {
  // console.log(config.url, '【浏览器请求前拦截】', config);
  const resultConfig = config;
  const tokenObj = base.getToken();
  if (tokenObj.token) {
    resultConfig.headers[base.token] = tokenObj.token;
  }
  resultConfig.url = base.API_PREFIX + resultConfig.url;
  if (resultConfig.url.endsWith('/login') || resultConfig.url.endsWith('/refresh')) {
    return resultConfig;
  }
  if (tokenObj.token && tokenObj.tokenExpireTime) {
    const now = Date.now();
    if (now >= tokenObj.tokenExpireTime) {
      if (!refresh) {
        refresh = true;
        request.refreshToken().then((res) => {
          if (res && res.data && res.data.authorization) {
            const token = res.data.authorization;
            requests.forEach((cb) => cb(token));
            requests = [];
          }
        }).finally(() => {
          refresh = false;
          return null;
        });
      }
      return new Promise((resolve) => {
        requests.push((token) => {
          resultConfig.headers[base.token] = token;
          resolve(resultConfig);
        });
      });
    }
  }
  return resultConfig;
}, (error) => {
  console.log('【浏览器请求失败】', error);
  return Promise.reject(error);
});
request.interceptors.response.use((res) => {
  // console.log(res.request.responseURL, '【服务器返回后拦截】', res);
  if (res.data.code === 403) {
    if (!base.logout) {
      console.log('删除过期token');
      base.clearToken();
    }
    console.log('跳转首页');
    router.push('/login');
    return Promise.reject();
  }
  return res;
}, (error) => {
  console.log('【服务器返回后出错】', error);
  // return Promise.resolve(error);
  return Promise.reject(error);
});
request.logout = () => request.get('/user/logout').then((res) => {
  base.clearToken();
  router.push('/login');
  return Promise.resolve(res);
});
request.refreshToken = () => request.get('/user/refresh').then((res) => {
  base.setToken(res);
  return Promise.resolve(res);
});
export default request;
